
#include "epoll_chat_tcp.h"
int main(int argc, char *argv[])
{
    int fd_listen = tcp_server_init("0", 8888, 40);
    ERROR_CHECK(-1, fd_listen, "tcp_server_init");
    int fd_ep = epoll_create(1);
    ERROR_CHECK(-1, fd_ep, "epoll_create");
    struct epoll_event event, ready_events[64];
    event.data.fd = fd_listen;
    event.events = EPOLLIN;
    int ret = epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_listen, &event);
    ERROR_CHECK(ret, -1, "epoll_ctl");
    ND *fd_list = createList();
    while (1)
    {
        ret = epoll_wait(fd_ep, ready_events, 64, -1); // read_events是以一个结构体数组，
        ERROR_CHECK(ret, -1, "epoll_wait");
        for (size_t i = 0; i < ret; i++)
        {
            int fd = ready_events[i].data.fd;
            if (fd == fd_listen)
            {
                int fd_cnd = tcp_server_wait(fd);
                if (fd_cnd == -1)
                {
                    perror("tcp_server_wait");
                    continue;
                }
                event.data.fd = fd_cnd;
                event.events = EPOLLIN;
                if (-1 == epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_cnd, &event))
                {
                    perror("epoll_ctl->ADD");
                    close(fd_cnd);
                    return -1;
                }
                insertNodeHead(fd_list,fd_cnd);
               
                
            }
            else
            {
                char buf[1024];
                int len_ret = recv(fd,buf,1024,MSG_PEEK);
        
                if (-1 == sendMsg(fd_list, fd) || len_ret ==0)
                {
                    perror("sendMsg");
                    struct sockaddr_in caddr;
                    socklen_t len = sizeof caddr;
                    getpeername(fd, (void *)&caddr, &len);
                    if (-1 == epoll_ctl(fd_ep, EPOLL_CTL_DEL, fd, NULL))
                    {
                        perror("epoll_ctl->DEL");
                        return -1;
                    }
                    delVal(fd_list,fd);
                    close(fd);
                    printf("client:%s:%d disconnected!\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
                }
            }
        }
    }

    return 0;
}
